<template>
  <div class="my-courses">
    <div class="page-header">
      <h1>我的课程</h1>
      <p>查看已选课程和学习进度</p>
    </div>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon courses">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalCourses }}</h3>
              <p>已选课程</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon credits">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalCredits }}</h3>
              <p>总学分</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon gpa">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.averageGrade || '--' }}</h3>
              <p>平均成绩</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon status">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.completedCourses }}</h3>
              <p>已完成</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="课程状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="selected" />
            <el-option label="已完成" value="completed" />
            <el-option label="已退课" value="dropped" />
          </el-select>
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="filterForm.semester" placeholder="选择学期" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="2024春季" value="2024-spring" />
            <el-option label="2024秋季" value="2024-fall" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :icon="Search">筛选</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>课程列表</span>
          <div>
            <el-button type="primary" @click="handleExport" :icon="Download" size="small">
              导出成绩单
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="courses" v-loading="loading" @row-click="handleRowClick">
        <el-table-column prop="course_code" label="课程代码" width="120" />
        <el-table-column prop="course_name" label="课程名称" min-width="200">
          <template #default="scope">
            <div class="course-info">
              <div class="course-name">{{ scope.row.course_name }}</div>
              <div class="course-desc" v-if="scope.row.course_description">
                {{ scope.row.course_description }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="teacher_name" label="授课教师" width="120" />
        <el-table-column prop="selection_date" label="选课时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.selection_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="成绩" width="100" align="center">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.grade"
              :type="getGradeType(scope.row.grade)"
              size="small"
            >
              {{ scope.row.grade }}
            </el-tag>
            <span v-else class="no-grade">未录入</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.stop="handleViewDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.status === 'selected'"
              type="danger"
              size="small"
              @click.stop="handleDropCourse(scope.row)"
            >
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="detailDialog.title"
      width="600px"
    >
      <div v-if="detailDialog.course" class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程代码">
            {{ detailDialog.course.course_code }}
          </el-descriptions-item>
          <el-descriptions-item label="课程名称">
            {{ detailDialog.course.course_name }}
          </el-descriptions-item>
          <el-descriptions-item label="学分">
            {{ detailDialog.course.credit }}
          </el-descriptions-item>
          <el-descriptions-item label="授课教师">
            {{ detailDialog.course.teacher_name }}
          </el-descriptions-item>
          <el-descriptions-item label="选课时间">
            {{ formatDate(detailDialog.course.selection_date) }}
          </el-descriptions-item>
          <el-descriptions-item label="当前成绩">
            <el-tag 
              v-if="detailDialog.course.grade"
              :type="getGradeType(detailDialog.course.grade)"
            >
              {{ detailDialog.course.grade }}
            </el-tag>
            <span v-else>未录入</span>
          </el-descriptions-item>
          <el-descriptions-item label="课程描述" :span="2">
            {{ detailDialog.course.course_description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-actions" style="margin-top: 20px; text-align: center;">
          <el-button 
            v-if="detailDialog.course.status === 'selected'"
            type="danger"
            @click="handleDropCourse(detailDialog.course)"
          >
            退课
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Reading, 
  Trophy, 
  Star, 
  CircleCheck, 
  Search, 
  Refresh, 
  Download 
} from '@element-plus/icons-vue'
import { getMyEnrollments, dropCourse } from '@/api/selection'

const loading = ref(false)
const courses = ref([])
const total = ref(0)

const filterForm = reactive({
  status: '',
  semester: ''
})

const pagination = reactive({
  page: 1,
  limit: 20
})

const detailDialog = reactive({
  visible: false,
  title: '',
  course: null
})

// 统计信息
const stats = computed(() => {
  const totalCourses = courses.value.length
  const totalCredits = courses.value.reduce((sum, course) => sum + (course.credit || 0), 0)
  const completedCourses = courses.value.filter(course => course.status === 'completed').length
  const gradesWithScore = courses.value.filter(course => course.grade && !isNaN(course.grade))
  const averageGrade = gradesWithScore.length > 0 
    ? (gradesWithScore.reduce((sum, course) => sum + parseFloat(course.grade), 0) / gradesWithScore.length).toFixed(1)
    : null

  return {
    totalCourses,
    totalCredits,
    completedCourses,
    averageGrade
  }
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 获取成绩类型
const getGradeType = (grade) => {
  const score = parseFloat(grade)
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'selected': return 'success'
    case 'completed': return 'info'
    case 'dropped': return 'danger'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'selected': return '进行中'
    case 'completed': return '已完成'
    case 'dropped': return '已退课'
    default: return '未知'
  }
}

// 获取我的选课列表
const fetchMyCourses = async () => {
  try {
    loading.value = true
    const params = {
      ...pagination,
      ...filterForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getMyEnrollments(params)
    if (response.code === 0) {
      courses.value = response.data.selections
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 退课操作
const handleDropCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要退选《${course.course_name}》这门课程吗？`,
      '确认退课',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await dropCourse({ courseId: course.course_id })
    if (response.code === 0) {
      ElMessage.success('退课成功！')
      detailDialog.visible = false
      fetchMyCourses() // 重新获取列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退课失败:', error)
    }
  }
}

// 查看详情
const handleViewDetails = (course) => {
  detailDialog.course = course
  detailDialog.title = `课程详情 - ${course.course_name}`
  detailDialog.visible = true
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewDetails(row)
}

// 筛选
const handleFilter = () => {
  pagination.page = 1
  fetchMyCourses()
}

// 重置
const handleReset = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  pagination.page = 1
  fetchMyCourses()
}

// 导出成绩单
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  fetchMyCourses()
}

const handleCurrentChange = () => {
  fetchMyCourses()
}

onMounted(() => {
  fetchMyCourses()
})
</script>

<style scoped>
.my-courses {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 20px;
  color: white;
}

.stat-icon.courses {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.credits {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.gpa {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.status {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 4px 0;
  font-weight: 600;
}

.stat-info p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info .course-name {
  font-weight: 500;
  color: #303133;
}

.course-info .course-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.no-grade {
  color: #c0c4cc;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.course-detail {
  padding: 10px 0;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style> 